package com.solon.open.controller;

import com.alibaba.dashscope.embeddings.MultiModalEmbeddingResult;
import com.alibaba.dashscope.exception.NoApiKeyException;
import com.alibaba.dashscope.exception.UploadFileException;
import com.solon.open.entity.QaReq;
import com.solon.open.model.QaModel;
import com.solon.open.service.EmbeddingService;
import com.solon.open.service.QaService;
import org.noear.solon.annotation.*;
import org.noear.solon.core.handle.UploadedFile;
import org.ttzero.excel.reader.ExcelReader;

import java.io.IOException;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

@Controller
public class QaController {
    @Inject
    private EmbeddingService embeddingService;
    @Inject
    private QaService qaService;

    /**
     * 导入qa测试数据
     * @param file
     * @return
     * @throws NoApiKeyException
     * @throws UploadFileException
     * @throws IOException
     */
    @Mapping("/upload/qa")
    @Post
    public String upload(UploadedFile file) throws NoApiKeyException, UploadFileException, IOException {
        try (ExcelReader reader = ExcelReader.read(file.getContent())) {
            List<QaModel> qaModels = reader.sheet(0)
                    .rows()// 读取数据行
                    .map(row -> row.to(QaModel.class))
                    .filter(Objects::nonNull)
                    .collect(Collectors.toList());
            for (QaModel qaModel : qaModels) {
                MultiModalEmbeddingResult multiModalEmbeddingResult = embeddingService.embedding(0, Collections.singletonList(qaModel.getQuestion()));
                qaModel.setQuestionVector(multiModalEmbeddingResult.getOutput().getEmbedding().stream()
                        .map(d -> d.floatValue())
                        .collect(Collectors.toList()));
            }
            qaService.addQa(qaModels);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "success";
    }

    /**
     * 问答
     * @param req
     * @return
     * @throws NoApiKeyException
     * @throws UploadFileException
     */
    @Mapping("/question")
    @Post
    public String question(@Body QaReq req) throws NoApiKeyException, UploadFileException {
        MultiModalEmbeddingResult multiModalEmbeddingResult = embeddingService.embedding(0, Collections.singletonList(req.getQuestion()));
        return qaService.getQa(req.getQuestion(),multiModalEmbeddingResult.getOutput().getEmbedding().stream()
                .map(d -> d.floatValue())
                .collect(Collectors.toList()));
    }
}